#coding: utf-8
class CulturalHeritage::Transfer < ActiveRecord::Base
  belongs_to :obj_cultural_institution_origin, :class_name => 'CulturalHeritage::CulturalInstitution', :foreign_key => 'origin'
  belongs_to :obj_cultural_institution_destiny, :class_name => 'CulturalHeritage::CulturalInstitution', :foreign_key => 'destiny'  
  belongs_to :obj_responsable, :class_name => 'User', :foreign_key => 'responsable'
  belongs_to :obj_creator, :class_name => 'User', :foreign_key => 'creator'

  has_many :list_heritage_x_transfer, :class_name => 'CulturalHeritage::MyHeritageXTransfer', :foreign_key => 'transfer'
  
  default_scope where("cultural_heritage_transfers.deleted = 0")

  #has_many :obj_cultural_heritage, :class_name => 'CulturalHeritage::CulturalHeritage', :foreign_key => 'cultural_heritage'

  def str_state
    if state == 0
      return "Registrado"
    end
    if state == 1
      return "En traslado"
    end
    if state == 2
      return "Recepcionado"
    end
  end

  def self.count_cultural_heritage_dependencies(id)
      return find(:all,:conditions=>["cultural_heritage_transfers.cultural_heritage = ? and (cultural_heritage_transfers.deleted = ?) ",id,0],:select=>"count(*) as 'transfers'")[0].transfers.to_i
  end

  def self.count_culturalInstitution_dependencies(id)
      return find(:all,:conditions=>["(cultural_heritage_transfers.origin  = ? or cultural_heritage_transfers.destiny  = ?) and (cultural_heritage_transfers.deleted = ?) ",id,id,0],:select=>"count(*) as 'transfers'")[0].transfers.to_i
  end

  def self.count_user_dependencies(id)
      return find(:all,:conditions=>["(cultural_heritage_transfers.responsable = ? or cultural_heritage_transfers.creator = ?) and (cultural_heritage_transfers.deleted = ?) ",id,id,0],:select=>"count(*) as 'transfers'")[0].transfers.to_i
  end
  
  def erasable
    herixtrans = CulturalHeritage::MyHeritageXTransfer.count_transfer_dependencies(id)
    if herixtrans >0
      return "Imposible borrar. Existen dependencias en patrimonio cultural por transferencias"          
    end
    return nil
  end
end
